/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.exporters.systems;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bugstat.common.TimeInterval;
import org.bugstat.common.utils.ProgressListener;
import org.bugstat.exporters.BugExporer;
import org.bugstat.exporters.BugPermanentInfoWriter;
import org.bugstat.exporters.BugTemporalInfoWriter;
import org.bugstat.exporters.ComponentReferenceStorage;
import org.bugstat.exporters.ConnectionManager;
import org.bugstat.exporters.ExportException;
import org.bugstat.exporters.ProductReferenceStorage;
import org.bugstat.exporters.RecordStorage;
import org.bugstat.exporters.StorageManager;
import org.bugstat.exporters.UserReferenceStorage;

/**
 * This class defines a base for classes that are able to export bug data from various bug tracking
 * systems.
 * 
 * @author Basil Shikin
 */
public abstract class BugExporterBase 
    implements BugExporer
{
    private static Log log = LogFactory.getLog( BugExporterBase.class );

    protected ConnectionManager connectionManager;
    protected StorageManager    storageManager;
    
   
    @Override
    public void setManagers(ConnectionManager connectionManager, StorageManager storageManager)
    {
        if ( connectionManager == null ) throw new IllegalArgumentException("Invalid connection manager specified");
        if ( storageManager == null ) throw new IllegalArgumentException("Invalid storage manager specified");
        
        this.connectionManager = connectionManager;
        this.storageManager    = storageManager;
    }


    /**
     * {@inheritDoc}
     */
    public void exportBugs(TimeInterval interval, final ProgressListener listener) throws ExportException
    {
        if ( connectionManager == null ) throw new IllegalStateException("No connection manager specified. Use setManagers().");
        if ( storageManager == null ) throw new IllegalStateException("No storage manager specified. Use setManagers().");
        
        log.info("Exporting bugs from " + interval.getStartDate() + " to " + interval.getEndDate() + " from " + getBugTrackerName() + "...");
        
        try
        {
            initializeExporter();
    
            notifyProgress( 1, listener );
            
            // Create export objects
            BugExportContext context = new BugExportContext();
            context.getPermWriter().writeHeader();
            
            // Load objects
            log.debug("Loading bug tracker users...");
            loadUsers( context.getUserStorage() );
            
            log.debug("Loading bug tracker components...");
            loadComponents( context.getComponentStorage() );
            
            log.debug("Loading bug tracker products...");
            loadProducts( context.getProductStorage() );
            
            notifyProgress( 5, listener );
            
            // Record storage will be re-used while creating bugs. Bug state will be loaded
            // in it, it will be flushed to disk every timeStep, updated with changes and saved
            // again on the next iteration.
            final RecordStorage recordStorage = storageManager.createRecordStorage( BugTemporalInfoWriter.HEADER_LENGTH );
            recordStorage.setRecordLength( BugTemporalInfoWriter.RECORD_LENGTH );

            int totalDateIntervals = interval.countSteps();
            int currentInteval     = 0;
            
            Date fromDate = interval.getStartDate();
            Date toDate   = interval.retrieveNextDate( fromDate );

            while ( toDate != null )
            {          
                log.debug("Processing bugs from " + fromDate + " to " + toDate + "..." );
                
                // Write new header
                context.getTempWriter().writeHeader( recordStorage );
                
                // Load status of all bugs into it
                populateBugChanges( fromDate, toDate, recordStorage, context );
                
                // Flush record storage to disk
                storageManager.saveRecordStorage(recordStorage, toDate);
                
                // Notify progress
                notifyProgress( Math.round( 5 + ( ++currentInteval*1F/totalDateIntervals*1F)*90F), listener );
                
                log.debug("Bugs from " + fromDate + " to " + toDate + " processed" );
                
                // Move to next date
                fromDate = toDate;
                toDate   = interval.retrieveNextDate( toDate );
            }
            
            log.debug("Saving objects..." );
            
            // Save permanent bug information
            storageManager.savePermStorage( context.getPermRecord(), BugPermanentInfoWriter.PERM_STORAGE_NAME );
            
            // Save all references
            storageManager.saveReferenceStorage( context.getUserStorage() );
            storageManager.saveReferenceStorage( context.getComponentStorage() );
            storageManager.saveReferenceStorage( context.getProductStorage() );
            
            notifyProgress( 100, listener );
        }
        catch (Throwable e)
        {
            log.error("Unable to export bugs from the bug tracker", e );
            
            throw new ExportException(e);
        }
        finally
        {
            log.debug("Shutting down exporter..." );
            
            shutdownExporter();
            
            log.debug("Exporter shut down" );
        }
        
        log.info("Bugs exported");
    }

    /**
     * Write changes that have happened in given interval for all bugs into given record storage. Use provided
     * <code>infoWriter</code> to write modifications and append bugs.
     * <p>
     * For example consider time interval from 01/01 to 07/01. If bugs 17 and 42 were closed and bug 69 was created,
     * this method should invoke <code>writeStatus()</code> for bugs 17 and 42 and then <code>appendBugInfo()</code>
     * for bug 69. Note that bug 69 should be fully populated.
     * </p> 
     * 
     * @param fromDate       Changes start date.
     * @param toDate         Changes end date.
     * @param recordStorage  Storage to write changes into.
     * @param context        Export context (contains objects used to write bug info). 
     *  
     * @throws SQLException 
     * @throws IOException 
     */
    protected abstract void populateBugChanges(Date fromDate, Date toDate, RecordStorage recordStorage, BugExportContext context) throws SQLException, IOException;
    
    
    /**
     * Initialize bug exporter. This method will be invoked every time exporting process starts.
     * 
     * @throws SQLException
     *             In case unable to initialize exporter
     */
    protected void initializeExporter() throws SQLException
    {
    }

    /**
     * Clean up and shutdown exporter. This method will be invoked after all bugs were exported.
     */
    protected void shutdownExporter()
    {
    }

    /**
     * Load available users (for faster access)
     * 
     * @param storage
     *            Storage to load users into. Guaranteed not to be null.
     * @throws SQLException
     *             In case unable to load users.
     */
    protected void loadUsers(final UserReferenceStorage storage) throws SQLException
    {
    }

    /**
     * Load available products (for faster access)
     * 
     * @param storage
     *            Storage to load products into. Guaranteed not to be null.
     * @throws SQLException
     *             In case unable to load products.
     */
    protected void loadProducts(final ProductReferenceStorage storage) throws SQLException
    {
    }

    /**
     * Load available components (for faster access)
     * 
     * @param storage
     *            Storage to load components into. Guaranteed not to be null.
     * @throws SQLException
     *             In case unable to load components.
     */
    protected void loadComponents(final ComponentReferenceStorage storage) throws SQLException
    {
    }

    
    protected void notifyProgress(int progress, ProgressListener listener)
    {
        if ( listener != null ) listener.progressReported( progress );
    }
}